<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/24
 * Time: 16:38
 */

namespace app\console\controller;
use think\Controller;
use think\Db;
use think\Request;
use app\console\model\SystemCard as Model;
use think\Url;
use think\View;


class SystemCard extends Controller
{
    /**
     * 前置方法
     */
    protected $beforeActionList = [
        'default_content' => ['create','update']
    ];
    public function default_content(){
        $default_content = Db::name('single')
            ->order(['sort' => 'asc','id' => 'asc'])
            ->where('parent_id',1)
            ->where('auding_status',2)
            ->where('is_delete',1)
            ->select();
        View::share('default_content',$default_content);
    }

    /**
     * @param $id
     * @return bool
     * 礼包数量删除
     */
    public function gift_count($id)
    {
        $ret = Db::name('system_card_count')->where('id',$id)->delete();
        if($ret){
            return true;
        }
        return false;
    }

    public function index(Model $model)
    {
        $param = Request::instance()->param();
        $where = [];
        if(!empty($param['title'])) $where['mc.title'] = ['like','%'.$param['title'].'%'];
        $data = $model
            ->alias('mc')
            ->field('mc.*')
            ->where($where)
            ->order(['mc.sort' => 'asc','mc.id' => 'desc'])
            ->paginate(10, false, ['query' => $param]);
        return view('', ['data' => $data]);
    }

    public function daochu(Model $model){
        $param = Request::instance()->param();
        $where = [];
        if(!empty($param['title'])) $where['m.username'] = ['eq',$param['title']];
        $data = $model
            ->alias('mc')
            ->join('member m','mc.member_id = m.id','left')
            ->join('shop s','mc.shop_id = s.id','left')
            ->field('mc.*,m.username,s.shop_title')
            ->where($where)
            ->order('mc.id','desc')
            ->paginate(10000, false, ['query' => $param])->toArray();
        if(!empty($data)){
            foreach ($data['data'] as $k => &$v){
                if(empty($v['shop_title'])){
                    $v['shop_title'] = '平台发放';
                }
                switch ($v['type']){
                    case 1;
                    $v['type'] = '年卡';
                    break;
                    case 2;
                    $v['type'] = '次卡';
                    break;
                }
                switch ($v['count']){
                    case 10000;
                        $v['count_type'] = '无限';
                        break;
                    default;
                        $v['count_type'] = $v['count'].'('.$v['minus_count'].')';
                }

            }
        }

        $this->push_coupon($data['data'],'用户会员卡导出');
    }
    public function push_coupon($data,$name = 'Excel')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '会员卡用户')
            ->setCellValue('C1', '发放门店')
            ->setCellValue('D1', '会员卡类型')
            ->setCellValue('E1', '总次数-剩余次数')
            ->setCellValue('F1', '开始时间 / 结束时间')
            ->setCellValue('G1', '发放时间')

        ;
        $sheet1 = ['A', 'B', 'C', 'D', 'I'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['id'])
                ->setCellValue('B' . $num, $v['username'])
                ->setCellValue('C' . $num, $v['shop_title'])
                ->setCellValue('D' . $num, $v['type'])
                ->setCellValue('E' . $num, $v['count_type'])
                ->setCellValue('F' . $num, $v['start_time'].'/'.$v['end_time'])
                ->setCellValue('G' . $num, $v['create_time'])
            ;

            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('用户会员卡导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    public function update($id, Request $request, Model $coupon)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();

            $dispose = $coupon->allowField(true)->save($data, ['id' => $id]);
            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }
            fail('操作失败');
        }

        $item = Model::get($id);

        $single_list = \app\console\model\Single::order(['sort' => 'asc','id' => 'asc'])->where(['auding_status' =>2,'is_delete'=>1])->where('parent_id',0)->select();
        $single_list2 = \app\console\model\Single::order(['sort' => 'asc','id' => 'asc'])->where(['auding_status' =>2,'is_delete'=>1])->where('parent_id','neq',0)->select();
        $single_list = getMenuTree($single_list);

        $gift_count = Db::name('system_card_count')->where('gift_id',$id)->select()->toArray();
        foreach ($gift_count as &$v){
            $v['two_array'] = Db::name('single')->where('parent_id',$v['single_id'])->where(['auding_status' => 2,'is_delete' => 1])->select();
        }

        return $this->fetch('create', [
            "mate_title" => '会员卡',
            'item' => $item,
            'member_list' => Db::name('member')->select(),
            'gift_count' => $gift_count,
            'single_list' => json_encode($single_list),
            'single_list2' => json_encode($single_list2),

        ]);
    }

    public function create(Request $request, Model $coupon)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();

            $dispose = $coupon->allowField(true)->save($data);
            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }
            fail('操作失败');
        }
        if(session('auding_status') == 1){
            //$shop_id = session('shop_id');
        }else{
            //$shop_id = 0;
        }

        $single_list = \app\console\model\Single::order(['sort' => 'asc','id' => 'asc'])->where(['auding_status' =>2,'is_delete'=>1])->where('parent_id',0)->select();
        $default_content = Db::name('single')->order(['sort' => 'asc','id' => 'asc'])->where('parent_id',1)->select();
        $single_list = getMenuTree($single_list);
        return $this->fetch('create', [
            "mate_title" => '会员卡',
            'member_list' => Db::name('member')->select(),
            'single_list' => json_encode($single_list),
//            'default_content' => json_encode($default_content),
            'gift_count' => []

        ]);
    }

    public function destroy($id)
    {
        $ret = (new \app\console\model\SystemCard())->where('id', $id)->delete();
        if ($ret) {
            win('删除成功', Url::build('index'));
        }
        fail('删除失败');
    }

    public function type($id = '')
    {
        if (Request::instance()->isAjax()) {
            $value = Db::name('system_card')->where('id', $id)->value('type');
            return $value;
        }
    }

    /**
     * 栏目状态改变
     */
    public function dc($id, Request $request, Model $model)
    {
        $id = $request->instance()->param('id');

        $status = $model->where('id', $id)->value('dc') == '1' ? 2 : 1;

        if ($model->where('id', $id)->update(['dc' => $status])) {
            return $status;
        }
        return false;
    }

    /**
     * 更新科目代码
     */
    public function code()
    {
        $param = Request::instance()->param()['code'];

        if (!empty($param)) {

            foreach ($param as $k => $v) {

                $ret = Db::name('system_card')->where('id', $k)->setField('code', $v);
            }
            if ($ret !== false) {
                win('科目代码设置成功', Url::build('index'));
            }
        }

    }

    /*
 * 排列顺序
 */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        if($id){
            foreach ($id as $key => $value) {
                Db::name('system_card')->where('id', $value)->update(['sort' => $sort[$key]]);
            }
        }

        win('操作成功', Url::build('index', ['orderId' => 'sort']));
    }

    public function status($id, Request $request, Model $model)
    {
        $id = $request->instance()->param('id');

        $status = Db::name('system_card')->where('id', $id)->value('status') == '1' ? 2 : 1;

        if (Db::name('system_card')->where('id', $id)->update(['status' => $status])) {
            return $status;
        }
        return false;
    }
}